package com.leetroll.app.controller;

import com.leetroll.api.service.UserActionService;
import com.leetroll.app.utils.AppJwtTokenUtil;
import com.leetroll.common.bean.ApiResponse;
import com.leetroll.common.entity.UserAction;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;


@RestController
@RequestMapping("/action")
@Api(value = "用户动作接口", tags = {"用户动作接口"})
@Slf4j
public class UserActionController {
    private final AppJwtTokenUtil jwtTokenUtil;
    private final UserActionService userActionService;

    @Autowired
    public UserActionController(AppJwtTokenUtil jwtTokenUtil, UserActionService userActionService) {
        this.jwtTokenUtil = jwtTokenUtil;
        this.userActionService = userActionService;
    }

    @ApiOperation(value = "切换动作", notes = "切换动作")
    @GetMapping("/toggle")
    public ApiResponse<Boolean> add(HttpServletRequest request,
                                    @RequestParam(value = "itemId") Long itemId,
                                    @RequestParam(value = "action") String action) {
        Long userId = jwtTokenUtil.getUserId(request);
        UserAction userAction = userActionService.getByAction(itemId, action);
        if (userAction == null) {
            userAction = new UserAction(userId, itemId, action);
            userAction.insert();
        } else {
            userAction.setValue(!userAction.getValue());
            userAction.updateById();
        }
        log.info("user:{} {}[{}] item:{}", userId, action, userAction.getValue(), itemId);
        return ApiResponse.OK(userAction.getValue());
    }

}
